<?php
namespace Application\Api\Controller;

class Product extends Base
{

    private function getService()
    {
        return $this->get(SERVICE_PRODUCT);
    }

    /*
        /Api/Product/getList
    */
    public function getListAction()
    {
        $data = $this->getRequestData();
        $categoryId = (int)tryGet($data, 'categoryId', 0);
        $recommendIn = tryGet($data, 'recommendIn', 0);
        $page = (int)tryGet($data, 'page', 1);
        $limit = (int)tryGet($data, 'limit', 10);
        $temp = $this->getService()->getList($categoryId, $recommendIn, $page, $limit);
        $list = $this->get(SERVICE_FILE)->getFileData($temp['list'], ['dry_image' => 1, 'dry_banner' => 2, 'dry_detail_image' => 1]);
        $send = [
            'oss_domain' => getOssDomain(),
            'list' => $list
        ];
        $send = addPageInformation($send, $page, $limit, $temp['count']);
        $this->sendSuccess($send);
    }

    /*
        获取优惠码的减免金额
        /Api/Product/getCodeDiscount
    */
    public function getCodeDiscountAction()
    {
        $data = $this->getRequestData();
        $code = tryGet($data, 'code', '');
        $mainProduct = tryGet($data, 'mainProduct', '');
        if(empty($code)){
            $this->sendFail('PARAMETER_ERROR', '请输入正确的优惠码', __LINE__);
            return false;
        }
        $userId = (int)parseUserCode($code);
        if($userId <= 0){
            $this->sendFail('PARAMETER_ERROR', '请输入正确的优惠码', __LINE__);
            return false;
        }
        if(empty($mainProduct)){
            $this->sendFail('PARAMETER_ERROR', '', __LINE__);
            return false;
        }
        $serviceProductAgent = $this->get(SERVICE_PRODUCTAGENT);
        $discount = $serviceProductAgent->getDiscount($userId, $mainProduct);
        if(!$discount){
            $this->sendFail('PARAMETER_ERROR', '请输入正确的优惠码', __LINE__);
            return false;
        }
        $send = [
            'discount' => formatPrice($discount)
        ];
        $this->sendSuccess($send);
        return false;
    }

    /*
        /Api/Product/getData
    */
    public function getDataAction()
    {
        $data = $this->getRequestData();
        $id = (int)tryGet($data, 'id', 0);
        if($id <= 0){
            $this->sendFail('PARAMETER_ERROR');
            return false;
        }
        $product = $this->getService()->one($id);
        if(empty($product)){
            $this->sendFail('PARAMETER_ERROR');
            return false;
        }
        $list = $this->get(SERVICE_FILE)->getFileData([$product], ['dry_image' => 1, 'dry_banner' => 2, 'dry_detail_image' => 1]);
        $send = [
            'oss_domain' => getOssDomain(),
            'product' => $list[0]
        ];
        $this->sendSuccess($send);
    }

}